#include "Poller.h"
#include "PlatLogger.h"
#include "StreamServer.h"
#include "StreamSocketChannel.h"
#include "Util.h"
namespace xncc {
namespace foundation {

    void Poller::kickInLoop(types::connection_id_t connId)
    {
        if (connIdFds_.find(connId) == connIdFds_.end()) {
            TRACE_ERROR << "conn:"_s << connId << " not found in conn map"_s;
            return;
        }
        auto iter = channels_.find(connIdFds_[connId]);
        if (iter == channels_.end()) {
            TRACE_ERROR << "conn:"_s << connId << " has been removed because of disconnect"_s;
            return;
        }
        if (iter->second->Type() == ChannelType::TCP_CHANNEL) {
            auto ptr = std::dynamic_pointer_cast<StreamSocketChannel>(iter->second);
            ptr->handleClose(shared::getDisconnectedReason(-2));
        }
        else {
            TRACE_ERROR << "channel type error, expected TCP_CHANNEL but is "_s << iter->second->Type();
        }
    }

    void Poller::addChannel(const std::shared_ptr<Channel>& chnl) { connIdFds_[chnl->connId()] = chnl->fd(); }

    void Poller::removeChannel(const std::shared_ptr<Channel>& chnl) { connIdFds_.erase(chnl->connId()); }
}  // namespace foundation
}  // namespace xncc